﻿using UnityEngine;
using Chat.Common;

public class ChatMsgHandle : IHandleable
{
    public void Handle(string cmd)
    {
        // ChatType|From|To|Msg
        int cmdSize = cmd.Length;
        int minCmdSize = Common.chtTypeSize + Common.idSize + Common.idSize;
        int msgSize = cmd.Length - minCmdSize;
        if (cmdSize >= minCmdSize)
        {
            
            string strChatType = cmd.Substring(0, Common.chtTypeSize).Trim();
            string strFromId = cmd.Substring(Common.chtTypeSize, Common.idSize).Trim();
            string strToId = cmd.Substring(Common.chtTypeSize + Common.idSize, Common.idSize).Trim();
            string msg = cmd.Substring(Common.chtTypeSize + Common.idSize + Common.idSize, msgSize);
            if (string.Compare(strChatType, ChatType.Private.ToString(), true) == 0) // 私聊
            {
                Message message = new Message
                {
                    ChatType = ChatType.Private,
                    Sender = Singleton<MemberManager>.GetInstance().GetMember(strFromId) as ChatObject,
                    Receiver = Singleton<MemberManager>.GetInstance().GetMember(strToId) as ChatObject,
                    Content = msg
                };
                Singleton<MessageManager>.GetInstance().AddMessage(message);
            }
            else if (string.Compare(strChatType, ChatType.Public.ToString(), true) == 0) // 群聊
            {
                Message message = new Message
                {
                    ChatType = ChatType.Public,
                    Sender = Singleton<MemberManager>.GetInstance().GetMember(strFromId) as ChatObject,
                    Receiver = Singleton<RoomManager>.GetInstance().GetRoom(strToId) as ChatObject,
                    Content = msg
                };
                Debug.Log(msg);
                Singleton<MessageManager>.GetInstance().AddMessage(message);
            }
            else
                Debug.Log("Chat type not available……");
        }
        else
            Debug.Log("Chat command not available……");
    }   
}
